import axios, { AxiosError, AxiosResponse, InternalAxiosRequestConfig } from '@ohos/axios';
import json from '@ohos.util.json';

const request = axios.create({
    // baseURL: 'http://192.168.174.38:6060',
    // baseURL: 'http://192.168.51.38:6060',
    baseURL: 'http://192.168.43.5:6060',
    // baseURL: 'http://192.168.43.5:6060',
    timeout: 20000,
})
request.interceptors.request.use(
    (config: InternalAxiosRequestConfig) => {
        // 未来需要添加 token
        // config.headers.token = token;
        return config;
    }
)
request.interceptors.response.use(
    (response: AxiosResponse) => {
        if (response.data.code === 200) {
            return response.data.data;
        } else {
            return Promise.reject(response.data.message);
        }
    },
    (error: AxiosError) => {
        return Promise.reject(error.message);
    }
)

export default class Http {
    get<T>(url: string, params?: Object) {
        console.log('get --- params' + " " + url + " " + json.stringify(params))
        return request.get<null, T>(url, {
            params
        })
    }

    post<T>(url: string, data?: Object) {
        console.log('post --- params' + " " + url + " " + json.stringify(data))
        return request.post<null, T>(url, data)
    }

    put<T>(url: string, data?: Object) {
        return request.put<null, T>(url, data)
    }

    delete<T>(url: string, params?: Object) {
        return request.delete<null, T>(url, {
            params
        })
    }
};